<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
</body>
<script>
// 标签页不刷新通信
// Connection to a broadcast channel
var bc = new BroadcastChannel('test_channel');
// 发送消息
bc.postMessage('This is a test message.');
// 接收消息
bc.onmessage = function (ev) { console.log(ev); }
//断开通道的连接
// bc.close()

function createId(name){
    const key = `channel-${name}`
    let id = + localStorage.getItem(key);
    if(!id){
        id =0 ;
    }
    id++;
    localStorage.setItem(key,id.toString())
    return id
}
function createChannel(name){
    const channel = new BroadcastChannel(name);
    channel.id = createId(name);
    channel.listeners=new Set();
    sendMsg('嘿',channel)
    window.addEventListener('unload',()=>{
        sendMsg('哦豁',channel);
    });
    channel.addEventListener('message',e=>{
        if(e.data.msg==='嘿'){
            sendMsg('哈',channel);
            channel.listeners.add(e.data.id);
        }else if(e.data.msg==='哈'){
            channel.listeners.add(e.data.id);
        }else if(e.data.msg==='哦豁'){
            channel.listeners.delete(e.data.id);
        }
    })
    return channel;
}
function sendMsg(msg,channel){
    channel.postMessage({
        id:channel.id,
        msg
    })
}
</script>
</html>